'''
Created on 09/04/2011

@author: lctr30
'''

import urllib
import urllib2


from core.pemba import Pemba



class Http(Pemba):
    POST = 'post'
    GET = 'get'
    TOKEN = '?'
    HTTP = 'http'
    TIMEOUT = 10.0
    def __init__(self, url=None, params=None, method=None, timeout=None):
        Pemba.__init__(self)
        self.url = url
        self.params = self.get_not_none(params, {}) 
        self.method = self.get_not_none(method, Http.POST)
        self.timeout = self.get_not_none(timeout, Http.TIMEOUT)
        
        
    def set_url(self, url):
        if self.is_none(url): return 
        self.url = url
        
    def set_param(self,key, value):
        if self.is_none(key) or self.is_none(value) : return
        self.params[key] = value
        
    def set_params(self, params):
        if self.is_none(params): return
        self.params = params
        
    def set_method(self,method):
        if self.is_none(method): return
        self.method = method
        
    def set_timeout(self, timeout):
        if self.is_none(timeout) : return
        self.timeout = timeout
        
    def set_poxy(self, server):
        if self.is_none(server): return
        #TODO proxy validation
        proxy = urllib2.ProxyHandler({Http.HTTP:server})
        opener = urllib2.build_opener(proxy)
        urllib2.install_opener(opener)
        
    def open(self):
        if self.is_none(self.url):return
        data = urllib.urlencode(self.params)
        if self.method == Http.POST:
            res = urllib2.urlopen(self.url, data, self.timeout)
            return res.read()
        else:
            url = Http.TOKEN.join([self.url, data])
            res = urllib2.urlopen(url, None, self.timeout)
            return res.read()
        
if __name__ == '__main__':
    req = Http()
    req.set_url('http://www.atmosphir.com/level/show')
    req.set_param('id', '440542')
    req.set_method(Http.GET)
    print req.open()
        
